package jlib.component.net
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	internal final class StepByStepStrategy extends EventDispatcher implements ILoadModeStrategy
	{
		private var m_loaderList:Vector.<SingleLoader>;
		private var dataContainer:DataContainer;
		private var timer:Timer;
		private var urls:Array;
		private var params:Array;
		private var currentIndex:int;
		
		public function StepByStepStrategy(target:IEventDispatcher=null)
		{
			super(target);
			dataContainer = new DataContainer;
			m_loaderList = new Vector.<SingleLoader>;
			timer = new Timer(100);
			timer.addEventListener(TimerEvent.TIMER, nextLoad );
		}
		
		public function getDelay(): Number { return timer.delay; }
		public function setDelay($time:Number):void
		{
			timer.delay = $time;
		}
		
		public function getLoadedDataAt($index:int): *
		{
			return dataContainer.getDataAt($index);
		}
		
		public function getLoadedDataLength():int
		{
			return dataContainer.getDataLength();
		}
		
		public function getLoadedIndex($data:*): int
		{
			return dataContainer.getIndex($data);
		}
		
		public function removeLoadedDataAt($index:int):void
		{
			return dataContainer.removeDataAt($index);
		}
		
		public function load($urls:Array, $params:Array):void
		{
			urls = $urls;
			params = $params;
			
			for(var i:int=0;i<urls.length;i++) m_loaderList.push(new SingleLoader);
			
			nextLoad();
		}
		
		private function nextLoad(e:TimerEvent=null): void
		{
			timer.stop();
			if(hasNext()){
				var loader:SingleLoader = m_loaderList[currentIndex]; //var loader:UnityLoader = new UnityLoader;
				loader.addEventListener(Event.COMPLETE, onLoaded );
				loader.addEventListener(IOErrorEvent.IO_ERROR, dispatchEvent );
				loader.addEventListener(ProgressEvent.PROGRESS, dispatchEvent );
				if(params) loader.load(urls[currentIndex], params[currentIndex]);
				else  loader.load(urls[currentIndex]);
				currentIndex++;
			}else {
				timer.stop();
			}
		}
		
		private function onLoaded(e:Event): void
		{
			var loader:SingleLoader = e.target as SingleLoader;
			dataContainer.addData(loader.getData());
			dispatchEvent(new Event(Event.COMPLETE));
			if(isAllComplete()) this.dispatchEvent(new MultiLoadEvent(MultiLoadEvent.ALL_COMPLETE));
			timer.start();
		}
		
		public function getLoaderList(): Vector.<SingleLoader> 
		{
			return m_loaderList;
		}
		
		private function hasNext():Boolean
		{
			return (currentIndex < urls.length);
		}
		
		private function isAllComplete(): Boolean { return ( currentIndex == urls.length);}
		
	}//c
}